package com.frxuexi.lib_base

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.frxuexi.lib_base.entity.ApiResponse
import com.frxuexi.lib_base.entity.LocalDocEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import java.io.File

abstract class BaseViewModel<UiIntent:IUiIntent>:ViewModel() {
    //存放和管理意图的管道
    private val _uiIntent= Channel<UiIntent>(Channel.UNLIMITED)

    //可变的状态，用于更新UI
    private var _uiState= MutableStateFlow<IUiState>(IUiState.onLoading)
    val uiState:StateFlow<IUiState>
        get() = _uiState

    init {
        viewModelScope.launch {
            _uiIntent.receiveAsFlow().collect{
                handleIntent(it)
            }
        }
    }
    //处理意图
    abstract fun handleIntent(intent: UiIntent)

    /**
     * 发送意图
     */
    fun sendIntent(intent: UiIntent){
        viewModelScope.launch {
            _uiIntent.send(intent)
        }
    }

    /**
     * 网络请求
     */
    fun httpRequest(request:Flow<ApiResponse<Any>>,type: RequestType=RequestType.DEFAULT){
        viewModelScope.launch {
            request.flowOn(Dispatchers.IO)
                .catch {
                    Log.i("===",it.message.toString())
                }
                .collect{resp->
                    if(resp.statusCode==200){

                        _uiState.value=IUiState.onSuccess(resp.data?:resp.datas,type)
                    }else{
                        _uiState.value=IUiState.onError(resp.msg!!)
                    }
                }
        }
    }

    /**
     * room请求
     */
    fun roomRequest(request:Flow<Any>,type: RequestType=RequestType.DEFAULT){
        viewModelScope.launch {
            request.flowOn(Dispatchers.IO)
                .catch {
                    Log.i("===",it.message.toString())
                }
                .collect{resp->
                    if(resp!=null){
                        _uiState.value=IUiState.onSuccess(resp,type)
                    }else{
                        _uiState.value=IUiState.onError("操作失败")
                    }
                }
        }
    }


    fun scanFile(file: File){
        viewModelScope.launch {
            val list = mutableListOf<LocalDocEntity>()
            try {
                val files = file.listFiles()
                for(file in files){
                    list.add(LocalDocEntity(file.name,file.absolutePath))
                }
                _uiState.value=IUiState.onSuccess(list,RequestType.SCAN)
            }catch (ex:Exception){
                _uiState.value=IUiState.onError("没有目录")
            }
        }
    }

    fun download(url:String,path:File){
        viewModelScope.launch {
            DownLoadUtil.download(url,path).flowOn(Dispatchers.IO)
                .catch {
                    Log.i("===",it.message.toString())
                }
                .collect{
                    _uiState.value=it
                }
        }
    }

}